package com.zbkj.client.task;

import com.zbkj.client.utils.FileUtil;
import com.zbkj.common.model.client.digital.CustomDigitalPerson;
import com.zbkj.client.vo.CustomDpCjVo;
import com.zbkj.common.utils.OssUtil;
import com.zbkj.service.service.CustomDigitalPersonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@Component
public class CustomDpUrlUpdateTask {
    @Resource
    private CustomDigitalPersonService customDigitalPersonService;
    @Resource
    private ThreadPoolTaskScheduler taskScheduler;

    public void start(CustomDigitalPerson customDigitalPerson, CustomDpCjVo vo) {
        schedule(customDigitalPerson, vo, 0);
    }

    private void schedule(CustomDigitalPerson customDigitalPerson, CustomDpCjVo vo, int retryCount) {
        long delay = retryCount == 0 ? 0 : 2000; // 首次立即，后续2秒重试
        taskScheduler.schedule(() -> {
            try {
                doTask(customDigitalPerson, vo, retryCount);
            } catch (Exception e) {
                log.error("CustomDpUrlUpdateTask-定时任务异常", e);
            }
        }, new Date(System.currentTimeMillis() + delay));
    }

    private void doTask(CustomDigitalPerson customDigitalPerson, CustomDpCjVo vo, int retryCount) {
        if (customDigitalPerson == null || vo == null) return;
        // 重新查库获取最新对象
        CustomDigitalPerson latestPerson = customDigitalPersonService.getById(customDigitalPerson.getId());
        if (latestPerson == null  || latestPerson.getIsDel() == 1) {
            log.warn("CustomDpUrlUpdateTask-未找到定制数字人记录，id={}", customDigitalPerson.getId());
            return;
        }
        Integer userId = latestPerson.getUserId();
        Integer merId = latestPerson.getMerId();
        String picUrl = vo.getPic_url();
        String previewUrl = vo.getPreview_url();
        boolean success = true;
        try {
            //没更新过才去更新
            if (picUrl != null && !picUrl.isEmpty() && (latestPerson.getOssPicUrl() == null || latestPerson.getOssPicUrl().isEmpty())) {
                String fileTypeLoop = FileUtil.getExtensionWithURI(picUrl);

                String fileName = "pic_" + System.currentTimeMillis() + "." + fileTypeLoop;
                String ossPicUrl = OssUtil.uploadFromUrlToOss(picUrl, fileName, userId, merId, "image", "customdp", "client");
                if (ossPicUrl != null) {
                    latestPerson.setOssPicUrl(ossPicUrl);
                } else {
                    success = false;
                }
            }

            if (previewUrl != null && !previewUrl.isEmpty() && (latestPerson.getOssPreviewUrl() == null || latestPerson.getOssPreviewUrl().isEmpty())) {
                String fileTypeLoop1 = FileUtil.getExtensionWithURI(previewUrl);

                String fileName = "video_" + System.currentTimeMillis() + "." + fileTypeLoop1;
                String ossPreviewUrl = OssUtil.uploadFromUrlToOss(previewUrl, fileName, userId, merId, "video", "customdp", "client");
                if (ossPreviewUrl != null) {
                    latestPerson.setOssPreviewUrl(ossPreviewUrl);
                } else {
                    success = false;
                }
            }
            latestPerson.setUpdateTime(new Date());
            customDigitalPersonService.updateById(latestPerson);
        } catch (Exception e) {
            log.error("CustomDpUrlUpdateTask-异步上传OSS或更新数据库异常", e);
            success = false;
        }
        if (!success && retryCount < 3) {
            log.warn("CustomDpUrlUpdateTask-上传OSS或更新数据库失败，准备重试，第{}次", retryCount + 1);
            schedule(latestPerson, vo, retryCount + 1);
        } else if (!success) {
            log.error("CustomDpUrlUpdateTask-重试3次后仍失败");
        }
    }
} 